package com.aube.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.aube.R;
import com.aube.control.DataManager;
import com.aube.model.OptionItem;
import com.aube.model.OptionResultModel;
import com.aube.model.TimeLinePiece;
import com.aube.views.flowlayout.FlowLayout;
import com.aube.views.flowlayout.TagAdapter;
import com.aube.views.flowlayout.TagFlowLayout;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.UmengUtils;
import com.huyn.baseframework.utils.Utils;

import java.util.HashMap;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by huyaonan on 16/3/22.
 */
public class CardVoteNew extends BaseCardNew {

    private Context context;
    private View mGoodsLayout, mRoot;

    private ImageView mLogo;
    private TextView mTitle;

    private TagFlowLayout mVoteView;

    private int margin = 0;
    private int marginBottom = 0;

    private TagAdapter mAdapter;
    private Option[] mLabels;

    private View mClose;

    private View mTop, mVoteRoot;

    private int selectedIndex = -1;
    private AtomicBoolean mResultRevealed = new AtomicBoolean(false);

    public CardVoteNew(Context context) {
        this(context, null);
    }

    public CardVoteNew(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CardVoteNew(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;

        mRoot = LayoutInflater.from(getContext()).inflate(R.layout.layout_card_vote_new, this);

        mLogo = (ImageView) mRoot.findViewById(R.id.card_vote_logo);
        mTitle = (TextView) mRoot.findViewById(R.id.card_vote_title);

        mGoodsLayout = findViewById(R.id.card_vote_layout);

        mCollapse = (ImageView) findViewById(R.id.card_vote_collapse);

        mClose = findViewById(R.id.card_vote_close);
        mClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                close();
            }
        });

        mVoteView = (TagFlowLayout) findViewById(R.id.card_vote);
        mVoteRoot = findViewById(R.id.card_vote_root);

        mTop = findViewById(R.id.card_vote_top);
        mTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mVoteRoot.getVisibility() != View.VISIBLE) {
                    swithWindow(false, mVoteRoot);
                }
            }
        });

        mCollapse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                swithWindow(mVoteRoot.getVisibility() == View.VISIBLE, mVoteRoot);
                requestLayout();
            }
        });

        margin = getResources().getDimensionPixelOffset(R.dimen.card_margin_space);
        marginBottom = getResources().getDimensionPixelOffset(R.dimen.card_margin_bottom);
    }

    public void init(final TimeLinePiece data, ChannelDetail detail) {
        super.init(data, detail);
        mTitle.setText(data.title);
        if(StringUtils.isNotBlank(data.getImgUrl())) {
            ImageLoader.getInstance(context).fillImage(mLogo, data.getImgUrl());
        } else {
            mLogo.setVisibility(View.GONE);
            ImageLoader.getInstance(context).preloadBitmap(data.getImgTag(), new ImageLoader.IPreloadCallback<Bitmap>() {
                @Override
                public void onSuccess(Bitmap bitmap) {
                    if (bitmap == null)
                        return;

                    SpannableStringBuilder builder = new SpannableStringBuilder("[star]  " + data.title);
                    builder.setSpan(new ExtendImageSpan(getContext(), bitmap, getTextHeight()), 0, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    mTitle.setText(builder);
                }

                @Override
                public void onFail() {

                }
            });
        }

        selectedIndex = DataManager.getInstance(context).getIndex(mData.rid);

        setupLabels();
        fillData();

        if(data.isCardFold()) {
            mVoteRoot.setVisibility(View.GONE);
            mCollapse.setImageResource(R.drawable.icon_arrowup);
        } else {
            mCollapse.setImageResource(R.drawable.icon_arrowdown);
        }

        UmengUtils.reportUmengEvent(context, UmengUtils.SHOW_VOTE, UmengUtils.appendLabels(mData.title, mChannelDetail.videoid, mChannelDetail.videoTitle));
    }

    @Override
    public String getType() {
        return TYPE_VOTE;
    }

    private float getTextHeight() {
        Paint paint = mTitle.getPaint();
        return Math.abs(paint.ascent());
    }

    public void doNext() {
        if(selectedIndex >= 0 && iSender != null) {
            mResultRevealed.set(true);
            setupLabels();
            iSender.startSync(mData.rid, false);
        }
    }

    private void setupBgDrawble(View test, int color) {
        // 外部矩形弧度
        float[] outerR = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 };
        // 内部矩形与外部矩形的距离
//        RectF inset = new RectF(5, 5, 5, 5);

        RoundRectShape rr = new RoundRectShape(outerR, null, null);
        ShapeDrawable drawable = new ShapeDrawable(rr);
        //指定填充颜色
        drawable.getPaint().setColor(getResources().getColor(color));
        // 指定填充模式
        drawable.getPaint().setStyle(Paint.Style.FILL);
        test.setBackgroundDrawable(drawable);
    }

    public void fillData() {
        mAdapter = new TagAdapter<Option>(mLabels) {

            @Override
            public View getView(FlowLayout parent, int position, Option s) {
                View v = LayoutInflater.from(context).inflate(R.layout.item_label_vote, mVoteView, false);
                initView(v, position);
                return v;
            }
        };

        mVoteView.setAdapter(mAdapter);

        mVoteView.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                try {
                    if (position == selectedIndex)
                        position = -1;

                    DataManager.getInstance(getContext()).update(mData.rid, position);

                    String cancelId = null;
                    String optionId = mData.getOptionId(position);
                    if (selectedIndex >= 0)
                        cancelId = mData.getOptionId(selectedIndex);
                    if (mData != null)
                        report(mData.rid, optionId, cancelId, false);

                    selectedIndex = position;

                    DataManager.getInstance(context).updateOptionCount(cancelId, true);
                    DataManager.getInstance(context).updateOptionCount(optionId, false);

                    //change text color
                    setupLabels();

                    UmengUtils.reportUmengEvent(context, UmengUtils.TO_VOTE, UmengUtils.appendLabels(mData.getOptionValue(position), mData.title, mChannelDetail.videoid, mChannelDetail.videoTitle));

                    notifyDataChanged();

                    if (iSender != null && mData != null && !mResultRevealed.get())
                        iSender.startSync(mData.rid, false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int height = mGoodsLayout.getMeasuredHeight() + marginBottom;// + margin;

        int flowWidth = mVoteView.getMeasuredWidth();
        int topWidth = mTop.getMeasuredWidth();

        int width = flowWidth > topWidth ? flowWidth : topWidth;

        if(topWidth > flowWidth) {
            ViewGroup.LayoutParams params = mVoteView.getLayoutParams();
            params.width = topWidth;
        }
        if(topWidth < flowWidth) {
            ViewGroup.LayoutParams params = mTop.getLayoutParams();
            params.width = flowWidth;
        }

        mVoteRoot.measure(View.MeasureSpec.makeMeasureSpec(flowWidth, View.MeasureSpec.EXACTLY), 0);
//        mVoteView.measure(widthMeasureSpec, 0);
        mContentHeight = mVoteRoot.getMeasuredHeight();

        measureChild(getChildAt(0), View.MeasureSpec.makeMeasureSpec(width + margin * 2, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY));

        setMeasuredDimension(View.MeasureSpec.makeMeasureSpec(width + margin * 2, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY));
    }


    @Override
    public void syncData(OptionResultModel response) {
        //reset data & notifydatasetchange
        //init mLabels
        try {
            setupLabels();
            notifyDataChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void animShow(final View v) {
//        v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
//                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
//        final int width = v.getMeasuredWidth();
        if(v.getVisibility() != View.VISIBLE) {
//            ValueAnimator anim = ValueAnimator.ofFloat(0, 1);
//            anim.setDuration(100);
//            anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//                @Override
//                public void onAnimationUpdate(ValueAnimator animation) {
//                    float fraction = (float) animation.getAnimatedValue();
//                    v.setScaleX(fraction);
//                    v.setScaleY(fraction);
//                    LinearLayout.LayoutParams params = (LayoutParams) v.getLayoutParams();
//                    params.width = (int) (width * fraction);
//                    v.setLayoutParams(params);
//                }
//            });
//            anim.start();
            v.setVisibility(View.VISIBLE);
        } else {
//            LinearLayout.LayoutParams params = (LayoutParams) v.getLayoutParams();
//            params.width = width;
//            v.setLayoutParams(params);
        }
    }

    private void animHide(final View v) {
        if(v.getVisibility() != View.VISIBLE) {

        } else {
            v.setVisibility(View.GONE);
        }
    }

    private void initView(View v, int position) {
        View layout = v.findViewById(R.id.label_text_layout);
        TextView tv = (TextView) v.findViewById(R.id.label_text);
        tv.setText(mData.getOptionValue(position));

        TextView ratio = (TextView) v.findViewById(R.id.label_ratio);
        String label = mLabels[position].value;
        if(StringUtils.isNotBlank(label)) {
            ratio.setText(label);

            if(ratio.getVisibility() != View.VISIBLE) {
                animShow(ratio);
            }
        } else {
            animHide(ratio);
        }

        if(selectedIndex >= 0) {
            setupBgDrawble(layout, mLabels[position].bgColor);
            tv.setTextColor(getResources().getColor(mLabels[position].txtColor));
            ratio.setTextColor(getResources().getColor(mLabels[position].txtColor));
        } else {
            setupBgDrawble(layout, R.color.white);
            tv.setTextColor(getResources().getColor(R.color.black));
            ratio.setTextColor(getResources().getColor(mLabels[position].txtColor));
        }
    }

    private void notifyDataChanged() {
        int childCount = mVoteView.getChildCount();
        for(int i=0; i<childCount; i++) {
            View v = mVoteView.getChildAt(i);
            initView(v, i);
        }
    }


    private void setupLabels() {
        if(mData == null)
            return;
        HashMap<String, Integer> mSet = new HashMap<>();
        HashMap<String, Integer> mCountSet = new HashMap<>();

        int[] arrays = new int[mData.optionSize()];
        int count = 0;
        int index = 0;
        for(OptionItem item : mData.getOptions()) {
            count += DataManager.getInstance(context).getOptionCount(item.optionId);
            if(index == selectedIndex)
                arrays[index] = 0;
            else
                arrays[index] = DataManager.getInstance(context).getOptionCount(item.optionId);
            index++;
        }

        if(count > 0) {
            for (OptionItem item : mData.getOptions()) {
                mSet.put(item.optionId, Utils.calPercentInt(count, DataManager.getInstance(context).getOptionCount(item.optionId)));
                mCountSet.put(item.optionId, DataManager.getInstance(context).getOptionCount(item.optionId));
            }

            sort(arrays);

            reSortData(mSet);
        }

        mLabels = new Option[mData.optionSize()];
//        int index = 0;
        index = 0;
        for(OptionItem item : mData.getOptions()) {
            mLabels[index] = new Option(null);
            if(selectedIndex >= 0) {
//            mLabels[index] = new Option(item.optionValue + (mSet.containsKey(item.optionId)?appendPercentStr(mSet.get(item.optionId)):""));
                mLabels[index].value = (mSet.containsKey(item.optionId)?appendPercentStr(mSet.get(item.optionId)):"");
                if(index != selectedIndex) {
                    if(count > 0) {
                        int itemCount = mCountSet.get(item.optionId);
                        if (itemCount == 0) {
                            mLabels[index].bgColor = R.color.white;
                            mLabels[index].txtColor = R.color.black;
                        } else if (itemCount == arrays[0]) {
                            mLabels[index].bgColor = R.color.option_highest;
                            mLabels[index].txtColor = R.color.white;
                        } else if (itemCount == arrays[1]) {
                            mLabels[index].bgColor = R.color.option_higher;
                            mLabels[index].txtColor = R.color.white;
                        } else {
                            mLabels[index].bgColor = R.color.option_extra;
                            mLabels[index].txtColor = R.color.white;
                        }
                    } else {
                        mLabels[index].bgColor = R.color.white;
                        mLabels[index].txtColor = R.color.black;
                    }
                } else {
                    mLabels[index].bgColor = R.color.option_selected;
                    mLabels[index].txtColor = R.color.white;
                }
            }
            index++;
        }
    }

    private void sort(int[] arrays) {
        /**
         * 做一个排序
         */
        for (int i = 0; i < arrays.length; i++) {
            for (int j = i + 1; j < arrays.length; j++) {
                if (arrays[j] > arrays[i]) {
                    int tem = arrays[j];
                    arrays[j] = arrays[i];
                    arrays[i] = tem;
                }
            }
        }
    }

    public class Option {
        public String value;
        public int bgColor = R.color.option_extra;
        public int txtColor = R.color.white;

        public Option(String value) {
            this.value = value;
        }

    }

}
